package com.example.jzg.mvpdemo.baserx;

import android.content.Context;

import com.example.jzg.mvpdemo.R;
import com.example.jzg.mvpdemo.Utils.LoadingDialog;
import com.example.jzg.mvpdemo.base.AppContext;

import rx.Subscriber;

/**
 * des:订阅封装
 * Created by xsf
 * on 2016.09.10:16
 */

/********************使用例子********************/
/*_apiService.login(mobile, verifyCode)
        .//省略
        .subscribe(new RxSubscriber<User user>(mContext,false) {
@Override
public void _onNext(User user) {
        // 处理user
        }

@Override
public void _onError(String msg) {
        ToastUtil.showShort(mActivity, msg);
        });*/
public abstract class RxSubscriber<T> extends Subscriber<T> {

    private Context mContext;
    private String msg;
    private boolean showDialog=true;

    /**
     * 是否显示浮动dialog
     */
    public void showDialog() {
        this.showDialog= true;
    }
    public void hideDialog() {
        this.showDialog= true;
    }

    public RxSubscriber(Context context, String msg,boolean showDialog) {
        this.mContext = context;
        this.msg = msg;
        this.showDialog=showDialog;
    }
    public RxSubscriber(Context context) {
        this(context, AppContext.getAppContext().getString(R.string.content),true);
    }

    /**
     *
     * @param context
     * @param showDialog  //是否使用封装的dialog false不使用  true使用
     */
    public RxSubscriber(Context context,boolean showDialog) {
        this(context, AppContext.getAppContext().getString(R.string.content),showDialog);
    }

    @Override
    public void onCompleted() {
        if (showDialog)
            LoadingDialog.hideDialog();
    }
    @Override
    public void onStart() {
        super.onStart();
        if (showDialog) {
            try {
//                LoadingDialog.showDialogForLoading((Activity) mContext,msg,true);
                LoadingDialog.showDialog(mContext);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


    @Override
    public void onNext(T t) {
        _onNext(t);
    }
    @Override
    public void onError(Throwable e) {
        if (showDialog)
            LoadingDialog.hideDialog();
        e.printStackTrace();
        _onError(e.toString());
        //网络
//        if (!NetWorkUtils.isNetConnected(AppContext.getAppContext())) {
//            _onError(AppContext.getAppContext().getString(R.string.no_net));
//        }
//        //服务器
//        else if (e instanceof ServerException) {
//            _onError(e.getMessage());
//        }
//        //其它
//        else {
//            _onError(AppContext.getAppContext().getString(R.string.no_net));
//        }
    }

    protected abstract void _onNext(T t);

    protected abstract void _onError(String message);

}
